

bt.module({builder: function(bt) {
    var j$ = jQuery;
    var map;
    var markers = [];
    var polygons = [];
    var clusterer ;
    
    function addWaypoint(data) {
        var image = new google.maps.MarkerImage(STATIC_URL+'img/places_map_icon.png?v=20120919',
                new google.maps.Size(42, 34),
                new google.maps.Point(0, 0),
                new google.maps.Point(16, 30));

        var marker = new google.maps.Marker({
            position: data[0],
            map: map,
            icon: image
        });

        markers.push(marker);
    }

    function getData(point) {
        var items = point.children();
        var lat = parseFloat($(items[0]).text());
        var lon = parseFloat($(items[1]).text());
        var content = $(items[2]).text();
        var wp_id = null;
        if (items.length > 3)
            wp_id = $(items[3]).text();
        return [new google.maps.LatLng(lat, lon), content, wp_id];
    }

    var drawPolygons = function() {
        if(!regions) {
            return false;
        }
        var data = regions.coordinates;
        var latlngbounds = new google.maps.LatLngBounds();
        var i, j, k;
        for (i = 0; i < data.length; i++) {
            var a = data[i];
            for (j = 0; j < a.length; j++) {
                var polygon = [];
                var b = a[j];
                for (k = 0; k < b.length; k++) {
                    var lat = b[k][1];
                    var lng = b[k][0];
                    var point = new google.maps.LatLng(lat, lng);
                    polygon.push(point);
                    latlngbounds.extend(point);
                }
                polygons.push(polygon);
            }
        }
        var polygonOverlay = new google.maps.Polygon(
                {
                    paths: polygons,
                    map: map,
                    strokeColor: "#4D90FE",
                    strokeWeight: 2,
                    fillColor: "#4D90FE",
                    fillOpacity: 0.1
                });
        map.fitBounds(latlngbounds);
        return true;
    };

    var initMapWidget = function() {
        /* display the whole world */
        var options = {
            zoom: place_type == 5 ? 18 : 14, // place_type == 5 means POI page.
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map"), options);
        var has_region = drawPolygons();

        var points = j$('#map_data').children();
        var latlngbounds = new google.maps.LatLngBounds();
        var coordinates = [];

        for (var i = 0; i < points.length; i++) {
            var point = j$(points[i]);
            //var type = point.attr('class');
            var data = getData(point);
            addWaypoint(data);
            latlngbounds.extend(data[0]);
            coordinates.push(data[0]);
        }

        if(points.length == 1 || place_type == 5) {
            map.setCenter(coordinates[0]);
        }
        if(points.length == 0) {
            /* display the whole world */
            latlngbounds.extend(new google.maps.LatLng(70, 150));
            latlngbounds.extend(new google.maps.LatLng(-20, -210));
        }
        if(!has_region && place_type != 5) {
            map.fitBounds(latlngbounds);
        }
        /* if map looks too small, let it fit the world */
        if(map.getZoom() < 1) {
            latlngbounds = new google.maps.LatLngBounds();
            latlngbounds.extend(new google.maps.LatLng(70, 150));
            latlngbounds.extend(new google.maps.LatLng(-20, -210));
        }

        var clustererStyles = [];

        for(i = 0; i < 5; i ++) {
            var style = {
                textColor: "transparent",
                url: STATIC_URL+"img/places_map_icon.png?v=20120919",
                width: 42,
                height: 34
            };
            clustererStyles.push(style);
        }
        clusterer = new MarkerClusterer(map, markers, {
            gridSize: 15,
            styles: clustererStyles,
            minimumClusterSize: 1,
            calculator: function(markers) {
                return { text: "", index: 0, title: "" };
            }
        });
    };

    var initHotPhotoPaginator = function() {
        j$(".hot-photos .nav-bar .nav-item").click(function() {
            if(j$(this).hasClass("disabled")) {
                return;
            }
            var url = j$(this).data("url");
            j$(".hot-photos .photos").css("opacity", 0.7);
            j$(".hot-photos .ajax-indicator").show();
            j$.get(url, function(resp) {
                j$(".hot-photos").html(resp);
                initHotPhotoPaginator();
                initPhotoMetaEvent();
                ellipsis();
            }).always(function() {
                j$(".photos").opacity(1);
                j$(".hot-photos .ajax-indicator").hide();
            });
        });
    };

    var initAutoHotPhotoLoadMoreEvent = function() {
        var body = j$("body.new-header");
        j$(window).scroll(function() {
            if (j$(".hot-photos").attr("data-load-flag") == "1") {
                return;
            }
            if((j$(window).scrollTop() + j$(window).height()) + 10 >= body.height()) {
                j$(".hot-photos").attr("data-load-flag", "1");
                var load_more = j$("#load-more");
                if (load_more.data("url") === undefined) return;
                j$("#loading-hint").show();
                j$('#ajax-more').show();
                j$('#ajax-more').css("visibility", "visible");
                j$.ajax({
                    url: load_more.data("url"),
                    success: function(resp) {
                        if(resp) {
                            j$(".photos").append(resp);
                        } else {
                            j$("#load-more").slideUp();
                        }
                    }
                }).always(function() {
                    load_more.remove();
                    j$("#loading-hint").remove();
                    initPhotoMetaEvent();
                    ellipsis();
                    j$(".hot-photos").attr("data-load-flag", "0");
                });
            }
        });
    };

    var refreshVisitedWishedPanel = function() {
        j$.ajax({
            url: j$("#right .visited-wished").data("url"),
            success: function(resp) {
                j$("#right .visited-wished").html(resp);
                j$("#right .visited-wished .wished .btn").click(function() {
                    _wishToGo(j$(this));
                });
            }
        });
    };

    var _modify_count = function(obj, type, count) {
        var _count = count || 1;
        var old_string = obj.text();
        var num = parseInt(old_string);
        if (type === 'incr') {
            num += _count;
        } else {
            num -= _count;
        }
        obj.text(num);
    };

    var initPhotoMetaEvent = function() {
        j$(".photos .photo-wrapper").unbind("mouseenter");
        j$(".photos .photo-wrapper").mouseenter(function() {
            j$(this).find(".mask").show()
                .animate({"opacity": 1}, 150);
                //.show("drop", {"direction": "down"});
            j$(this).find(".mask").mouseenter(function(e) {
                e.stopPropagation();
            });
        });
        j$(".photos .photo-wrapper").unbind("mouseleave");
        j$(".photos .photo-wrapper").mouseleave(function() {
            if(j$(this).find(".mask").is(":visible")) {
                j$(this).find(".mask").animate({"opacity": 0}, 200, function() {j$(this).hide();});
                //j$(this).find(".mask").hide("drop", {"direction": "down"});
            }
        });

        j$(".photos .meta .like-btn").unbind("click");
        j$(".photos .meta .like-btn").click(function() {
            if(!BT_USER_ID) {
                return true;
            }
            if(j$(this).find(".icon").hasClass("ajax-icon")) {
                return false;
            }
            var _this = this;
            var trip_id = j$(this).data("trip_id");
            var waypoint_id = j$(this).data("waypoint_id");
            var recommended = j$(this).find(".icon").hasClass("liked-icon");
            var url = '/trips/' + trip_id + '/waypoints/' + waypoint_id + '/';
            url += recommended? 'delete_recommend/': 'recommend/';
            j$(_this).find(".icon").addClass("ajax-icon");
            $.ajax({
                url: url,
                dataType: 'json',
                type: 'POST',
                success: function(msg){
                    if (msg.error)
                        alert(msg.error);
                    else {
                        if (recommended) {
                            j$(_this).find(".icon").removeClass("liked-icon");
                        } else {
                            j$(_this).find(".icon").addClass("liked-icon");
                        }
                        _modify_count(j$(_this).find("span"), recommended? 'decr': 'incr');
                    }
                },
                error: function(){
                    alert("操作失败，请稍候再试");
                }
            }).always(function() {
                j$(_this).find(".icon").removeClass("ajax-icon");
            });
            return false;
        });
    };

    var ellipsis = function() {
        j$(".photos .mask .place-title").each(function() {
            j$(this).ThreeDots({max_rows: 1});
        });

        j$(".photos .mask .text").each(function() {
            j$(this).ThreeDots({max_rows: 5});
        });
        j$(".photos .photo-wrapper .mask").css("opacity", 0).css("z-index", 10);
    };


    var _wishToGo = function(btn) {
        if(bt.misc.isAuthenticated()) {
            var active = btn.hasClass("active");
            if(btn.hasClass("on-going")) {
                return false;
            }
            btn.addClass("on-going");
            j$.ajax({
                url: btn.data("url") + (active? "remove/": "add/"),
                type: "POST",
                success: function(resp) {
                    j$(".button-panel .wish-to-go").toggleClass("active");
                    if (j$.browser.msie && j$.browser.version == 6) {
                        if (j$(".button-panel .wish-to-go").hasClass("active")) {
                            j$(".button-panel .wish-to-go .icon").css("background-position", "-60px 0");
                        } else {
                            j$(".button-panel .wish-to-go .icon").css("background-position", "-30px 0");
                        }
                    }
                    refreshVisitedWishedPanel();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("操作失败，请稍候再试");
                }
            }).always(function() {
                btn.removeClass("on-going");
            });
        } else {
            bt.misc.redirect_to_login();
        }
    };

    var initButtons = function() {
        j$(".button-panel .wish-to-go").click(function() {
            _wishToGo(j$(this));
        });
        j$("#right .visited-wished .wished .btn").click(function() {
            _wishToGo(j$(this));
        });
    };

    var initLandscapeDescription = function() {
        if (!j$("#landscape-description .description")[0]) return;
        var target_div = j$("#landscape-description .panel-content .description");
        j$(".text", target_div).ThreeDots({max_rows: 7, whole_word: false});
        if (!j$(".text span.threedots_ellipsis", target_div)[0]) {
            j$(".check-more", target_div).hide();
        } else {
            j$(".check-more", target_div).click(function(){
                var content = j$(".text", target_div).attr("threedots");
                j$(".text", target_div).html("<span>" + content + "</span>");
                j$(this).remove();
            })
        }
    };

    j$(document).ready(function() {
        initButtons();
        initHotPhotoPaginator();
        initAutoHotPhotoLoadMoreEvent();
        initPhotoMetaEvent();
        initLandscapeDescription();
        refreshVisitedWishedPanel();
        ellipsis();

        j$(".place-item .name a").each(function() {
            j$(this).ThreeDots({
                max_rows: 1,
                alt_text_t: true,
                whole_word: false
            });
        });

        j$.ajax({
            url: j$("#map_data").data("url"),
            success: function(resp) {
                j$("#map_data").html(resp);
                initMapWidget();
            }
        });
    });

}});
